package br.com.hotstar.control.annotation.imp;

import java.util.Set;

import javax.annotation.Priority;
import javax.faces.application.FacesMessage;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import br.com.hotstar.control.annotation.TreatException;
import br.com.hotstar.control.base.BaseManagedBean;

@Interceptor @TreatException @Priority(Interceptor.Priority.APPLICATION)
public class TreatExceptionImp extends BaseManagedBean{
	
	@AroundInvoke
	public Object execute(InvocationContext contexto){
		 try{
	            
	          
	            Object methodResult = contexto.proceed();
	           
	            return methodResult;
	        
		 } catch (ConstraintViolationException e) {
			 Throwable t = e;
	            while (t != null) {
	                if (t instanceof ConstraintViolationException) {
	                    Set<ConstraintViolation<?>> constraintViolations = ((ConstraintViolationException) t).getConstraintViolations();
	                    for (ConstraintViolation<?> constraintViolation : constraintViolations) {
	                        FacesMessage facesMessage = new FacesMessage(constraintViolation.getMessage());
	                        facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
	                        context.addMessage(null, facesMessage);
	                    }
	                }
	                t = t.getCause();
	            }
		     return null;
			 
		 } catch (Throwable e) {
			 FacesMessage facesMessage = new FacesMessage(e.getMessage());
             facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
             context.addMessage(null, facesMessage);
		     e.printStackTrace();
		     return null;
		 }
	}

}
